import { createSp, updateSp } from '@/services/channel/sp_api';
import { ModalForm, ProForm,  ProFormRadio,  ProFormText } from '@ant-design/pro-components';
import { message } from 'antd';
import React, { useEffect, useState } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import {getApiList} from '@/services/channel/spapi_api'


interface CreateModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  values?: Partial<ServiceProvider>;
}

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
interface ApiOption {
    value: string;
    label: string;
}

const EditForm: React.FC<CreateModalProps> = ({ visible, values, onCancel, onSuccess }) => {
    const [form] = ProForm.useForm<ServiceProvider>();
    const intl = useIntl();
    const [apiOptions, setApiOptions] = useState<ApiOption[]>([]);
    const [loading, setLoading] = useState(false);
    const loadApiOptions = async () => {
        setLoading(true);
        try {
            const response = await getApiList();
            if (response.code === 0 && response.data) {
                setApiOptions(response.data.map((item: any) => ({
                    value: item.key,
                    label: item.value
                })));
            }
        } catch (error) {
            message.error(intl.formatMessage({ id: 'request.error.apiOptions' }));
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (visible) {
            form.resetFields();
            form.setFieldsValue({
                spStatus: '1',
                ...(values || {})
            });
            loadApiOptions(); // 打开模态框时加载API选项

        }
    }, [visible, values]);
    const handleSubmit = async (formValues: ServiceProvider) => {
      // console.log(values?.spId)
      // console.log(values)
        try {
            const response = values?.spId
                ? await updateSp({ ...formValues, spId: values.spId })
                : await createSp(formValues);

      if (response.code != 0) {
        message.error(intl.formatMessage({ id: 'request.error.operating' }) + response?.msg);
        return false;
      }

      message.success(intl.formatMessage({ id: 'request.success.operating' }));
      onSuccess();
      form.resetFields();
      return true;
    } catch (error) {
      message.error(intl.formatMessage({ id: 'request.error.retry' }));
      return false;
    }
  };

  return (
    <ModalForm<ServiceProvider>
      title={values?.asId
        ? intl.formatMessage({ id: 'pages.edit' })
        : intl.formatMessage({ id: 'pages.create' })}
      width={800}
      form={form}
      open={visible}
      onOpenChange={(visible) => !visible && onCancel()}
      onFinish={handleSubmit}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      submitter={{
        searchConfig: {
          submitText: intl.formatMessage({ id: 'pages.button.submit' }),
          resetText: intl.formatMessage({ id: 'pages.button.cancel' }),
        },
      }}
      layout="horizontal" {...formItemLayout}
    >
      <ProFormText
        name="spCode"
        label={intl.formatMessage({ id: 'pages.spForm.spCode' })}
        placeholder={intl.formatMessage({ id: 'pages.spForm.spCode.placeholder' })}
        disabled={!!values?.spId}
        rules={[{
          required: true,
          message: intl.formatMessage({ id: 'pages.spForm.spCode.required' })
        }]}
      />

      <ProFormText
        name="spName"
        label={intl.formatMessage({ id: 'pages.spForm.spName' })}
        placeholder={intl.formatMessage({ id: 'pages.spForm.spName.placeholder' })}
        rules={[{
          required: true,
          message: intl.formatMessage({ id: 'pages.spForm.spName.required' })
        }]}
      />

      <ProFormRadio.Group
        name="spStatus"
        label={intl.formatMessage({ id: 'pages.spForm.spStatus' })}
        rules={[{ required: true }]}
        options={[
          {
            label: intl.formatMessage({ id: 'pages.active' }),
            value: '0',
          },
          {
            label: intl.formatMessage({ id: 'pages.inactive' }),
            value: '1',
          },
        ]}
      />
      
      <ProFormText
        name="spContactPerson"
        label={intl.formatMessage({ id: 'pages.spForm.spContactPerson' })}
        placeholder={intl.formatMessage({ id: 'pages.spForm.spContactPerson.placeholder' })}
      />

      <ProFormText
        name="spContactPersonPhone"
        label={intl.formatMessage({ id: 'pages.spForm.spContactPersonPhone' })}
        placeholder={intl.formatMessage({ id: 'pages.spForm.spContactPersonPhone.placeholder' })}
      />

      <ProFormText
        name="spContactEmail"
        label={intl.formatMessage({ id: 'pages.spForm.spContactEmail' })}
        placeholder={intl.formatMessage({ id: 'pages.spForm.spContactEmail.placeholder' })}
      />

      <ProFormText
        name="spBalance"
        label={intl.formatMessage({ id: 'pages.spForm.spBalance' })}
        placeholder={intl.formatMessage({ id: 'pages.spForm.spBalance.placeholder' })}
      />
    </ModalForm>
  );
};

export default EditForm;